import logging
import re


from database.database_conf import DatabaseConf


class DatabaseObject:

    def __init__(self):
        self.db_conf = None
        self.db_url = None
        self.db_con = None
        self.last_error = None

    def get_last_error(self):
        return self.last_error

    def connect(self, db_conf: DatabaseConf) -> bool:
        pass

    def close(self) -> bool:
        if self.db_con:
            logging.info(f"close {self.db_url}")
            self.db_con.close()
            self.db_con = None
            return True
        return False

    def fetchone(self, sql, params=None):
        db_cur = None
        row = None
        try:
            logging.info(f"%s" % re.sub(r"\s+", " ", sql))
            db_cur = self.db_con.cursor()
            if params:
                logging.info(params)
                db_cur.execute(sql, params)
            else:
                db_cur.execute(sql)
            row = db_cur.fetchone()

        except Exception as e:
            self.last_error = str(e)
            logging.error(f"Exception %s, %s" % (re.sub(r"\s+", " ", sql), e))
        finally:
            if db_cur:
                db_cur.close()
        return row

    def fetchall(self, sql, params=None):
        db_cur = None
        rows = []
        try:
            logging.info(f"%s" % re.sub(r"\s+", " ", sql))

            db_cur = self.db_con.cursor()
            if params:
                logging.info(params)
                db_cur.execute(sql, params)
            else:
                db_cur.execute(sql)
            rows = db_cur.fetchall()
        except Exception as e:
            self.last_error = str(e)
            logging.error(f"Exception %s, %s" % (re.sub(r"\s+", " ", sql), e))
        finally:
            if db_cur:
                db_cur.close()
        return rows

    def fetchall_dict(self, sql, params=None):
        db_cur = None
        rows = []
        try:
            logging.info(f"%s" % re.sub(r"\s+", " ", sql))
            db_cur = self.db_con.cursor()
            if params:
                logging.info(params)
                db_cur.execute(sql, params)
            else:
                db_cur.execute(sql)
            columns = [col[0] for col in db_cur.description]
            rows = [dict(zip(columns, row)) for row in db_cur.fetchall()]

        except Exception as e:
            self.last_error = str(e)
            logging.error(f"Exception: {e}")
        finally:
            if db_cur:
                db_cur.close()
        return rows

    def get_version(self) -> str:
        pass

    def get_schema_list(self) -> list:
        pass

    def get_table_list(self, schema_name: str) -> list:
        pass

    def get_filed_list(self, schema_name: str, table_name: str) -> list:
        pass
